package cn.jhc.servlet;

import cn.jhc.utils.UniqueNameConverter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload2.core.DiskFileItem;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletDiskFileUpload;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
        String uploadPath = req.getServletContext().getRealPath("/upload");
        DiskFileItemFactory factory = DiskFileItemFactory.builder()
                .setBufferSizeMax(1024 * 1024)
                .setPath(uploadPath)
                .get();
        JakartaServletDiskFileUpload upload = new JakartaServletDiskFileUpload(factory);
        upload.setFileSizeMax(1024 * 1024 * 10);

        List<DiskFileItem> items = upload.parseRequest(req);
        for (DiskFileItem item : items) {
            if (item.isFormField())  {
                System.out.println(item.getFieldName() + " = " + item.getString());
            } else {
                String uniqueName = UniqueNameConverter.convert(item.getName());
                item.write(Path.of(uploadPath, uniqueName));
                req.getSession().setAttribute("avatar", uniqueName);
            }
        }
        
        resp.sendRedirect("./success.jsp");
    }
}
